package com.example.templatedemo

import android.Manifest
import android.util.Log
import androidx.annotation.OptIn
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.core.resolutionselector.AspectRatioStrategy
import androidx.camera.core.resolutionselector.ResolutionSelector
import androidx.camera.core.resolutionselector.ResolutionStrategy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.example.lib_common.base.BaseMvvmActivity
import com.example.templatedemo.HomeFragment.Companion.userLiveData
import com.example.templatedemo.data.model.User
import com.example.templatedemo.databinding.ActivityScanBinding
import com.google.common.util.concurrent.ListenableFuture
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage

class ScanActivity : BaseMvvmActivity<ActivityScanBinding, ScanVM>() {

    private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>
    override fun initView() {
        super.initView()
        mBinding.bt.setOnClickListener {
            userLiveData.postValue(User("Jane2", 28))
        }
        requestPer(Manifest.permission.CAMERA) {
            cameraProviderFuture = ProcessCameraProvider.getInstance(this)
            cameraProviderFuture.addListener({
                val cameraProvider = cameraProviderFuture.get()
                startCamera(cameraProvider)
            }, ContextCompat.getMainExecutor(this))
        }
    }

    @OptIn(ExperimentalGetImage::class)
    private fun startCamera(cameraProvider: ProcessCameraProvider) {
        val preview = Preview.Builder().build().also {
            it.surfaceProvider = mBinding.previewView.surfaceProvider
        }

        val barcodeScanner = BarcodeScanning.getClient()

        val resolutionSelector = ResolutionSelector.Builder()
            // 指定优先比例，例如 16:9
            .setAspectRatioStrategy(
                AspectRatioStrategy(
                    AspectRatio.RATIO_16_9,
                    AspectRatioStrategy.FALLBACK_RULE_AUTO
                )
            )
            // 优先高分辨率（适合扫码）
            .setResolutionStrategy(
                ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY
            )
            .build()

        /**
         * val imageAnalysis = ImageAnalysis.Builder()
         *     .setTargetAspectRatio(AspectRatio.RATIO_16_9) // 或 RATIO_4_3
         *     .setTargetRotation(Surface.ROTATION_0)
         *     .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
         *     .build()
         */
        /**
         * ImageAnalysis.Builder()
         *     .setTargetResolution(Size(1280, 720)) // 或更高
         *     .build()
         *
         */
        val analyzer =
            ImageAnalysis.Builder().setResolutionSelector(resolutionSelector)
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build().also {
                    it.setAnalyzer(ContextCompat.getMainExecutor(this)) { imageProxy ->
                        val mediaImage = imageProxy.image
                        if (mediaImage != null) {
                            val inputImage =
                                InputImage.fromMediaImage(
                                    mediaImage,
                                    imageProxy.imageInfo.rotationDegrees
                                )
                            barcodeScanner.process(inputImage)
                                .addOnSuccessListener { barcodes ->
                                    for (barcode in barcodes) {
                                        val rawValue = barcode.rawValue
                                        Log.d("SCAN", "识别结果: $rawValue")
                                        // 这里可以处理识别结果，例如跳转或回调
                                    }
                                }
                                .addOnCompleteListener {
                                    imageProxy.close()
                                }
                        }
                    }
                }

        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        cameraProvider.unbindAll()
        cameraProvider.bindToLifecycle(
            this, cameraSelector, preview, analyzer
        )
    }
}